package com.icehand.payment.pay.wechat.mini;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.icehand.common.constants.CommonConstants;
import com.icehand.common.enums.PayChannelEnum;
import com.icehand.common.enums.SignTypeEnum;
import com.icehand.mybatis.payment.mapper.PayNotifyRecordMapper;
import com.icehand.payment.model.PayWrapper;
import com.icehand.payment.pay.wechat.BaseWechatPay;
import com.icehand.payment.pay.wechat.WeChatPaymentUnifiedOrderRequest;
import com.icehand.payment.pay.wechat.WeChatPaymentUnifiedOrderResponse;
import com.icehand.wechat.mini.WechatMiniHelper;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.web.client.RestTemplate;

import static com.icehand.payment.pay.wechat.WeChatPaymentSignatureUtils.generateNonceStr;

/**
 * @author icehand
 */
@Slf4j
public class WechatMiniPay extends BaseWechatPay {
    private static final PayChannelEnum CHANNEL = PayChannelEnum.WECHAT_MINI_PAY;
    private final WechatMiniHelper wechatMiniHelper;

    public WechatMiniPay(RestTemplate restTemplate, XmlMapper xmlMapper, WechatMiniHelper wechatMiniHelper,
                         PayNotifyRecordMapper payNotifyRecordMapper) {
        super(restTemplate, xmlMapper, payNotifyRecordMapper);
        this.wechatMiniHelper = wechatMiniHelper;
    }

    @Override
    protected boolean isWechatPay(PayChannelEnum payChannelEnum) {
        return CHANNEL.equals(payChannelEnum);
    }

    @Override
    protected WeChatPaymentUnifiedOrderRequest createUnifiedOrder(PayWrapper payWrapper) {
        String openId = wechatMiniHelper.getOpneId(payWrapper.getConfig().getString(CommonConstants.K_APP_ID),
                payWrapper.getExtendMap().get("uid") == null ? null :  Long.valueOf(payWrapper.getExtendMap().get("uid")),
                payWrapper.getConfig().getString(CommonConstants.K_SECRET), payWrapper.getExtendMap().get(CommonConstants.K_CODE));
        return super.createUnifiedOrder(payWrapper)
                .setTrade_type("JSAPI")
                .setOpenid(openId);
    }

    @Override
    protected void doAfter(PayWrapper payWrapper, WeChatPaymentUnifiedOrderResponse response) {
        if(payWrapper.getBizResult().isSuccess()){
            WeChatMiniPayment weChatMiniPayment = new WeChatMiniPayment()
                    .setAppId(response.getAppId())
                    .setNonceStr(generateNonceStr())
                    .setTimestamp(new DateTime().getMillis()/1000 + "")
                    .setPackageStr("prepay_id="+response.getPrepayId())
                    .setSignType(SignTypeEnum.MD5.getType());
            weChatMiniPayment.createSign(payWrapper.getConfig().getString(CommonConstants.K_SECRET));
        }
    }

    @Override
    public PayChannelEnum getChannel() {
        return CHANNEL;
    }
}
